import 'package:cached_network_image/cached_network_image.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_smart_heating/common/app.dart';
import 'package:flutter_smart_heating/common/http.dart';
import 'package:flutter_smart_heating/mode/list_pagination_model.dart';
import 'package:flutter_smart_heating/ui/src/pull_to_refresh.dart';
import 'package:flutter_smart_heating/ui/ui.dart';
import 'package:get/get.dart';

class UserMessagerChattingPage extends StatefulWidget {
  const UserMessagerChattingPage({super.key});

  @override
  State<UserMessagerChattingPage> createState() =>
      _UserMessagerChattingPageState();
}

class _UserMessagerChattingPageState extends State<UserMessagerChattingPage> {
  String chattingName = '';
  String? chattingId;
  List<dynamic> list = [];
  ListPaginationModel pagination = ListPaginationModel();
  RefreshController refreshController = RefreshController();
  bool refreshing = false;
  bool loading = true;
  final listenable = IndicatorStateListenable();
  bool _shrinkWrap = true;
  double? _viewportDimension;

  @override
  void initState() {
    chattingName = Get.parameters['name'] ?? '对话消息';
    chattingId = Get.parameters['id'];
    listenable.addListener(onHeaderChange);
    super.initState();
  }

  @override
  void dispose() {
    listenable.removeListener(onHeaderChange);

    super.dispose();
  }

  void onHeaderChange() {
    final state = listenable.value;
    if (state != null) {
      final position = state.notifier.position;
      _viewportDimension ??= position.viewportDimension;
      final shrinkWrap = state.notifier.position.maxScrollExtent == 0;
      if (_shrinkWrap != shrinkWrap &&
          _viewportDimension == position.viewportDimension) {
        setState(() {
          _shrinkWrap = shrinkWrap;
        });
      }
    }
  }

  fetchData() async {
    var res = await Http.instance.post(
      '/plugin/messager/api/index',
      data: {
        "page": pagination.currentPage,
        "cate_id": chattingId,
      },
    );
    if (res.code == 1) {
      if (pagination.currentPage <= 1) {
        list.clear();
      }
      pagination = ListPaginationModel.fromJson(res.data);
      res.data['data'].forEach(
        (item) => list.add(item),
      );
    }
    list = list.reversed.toList();
    for (var i = list.length - 1; i >= 0; i--) {
      if (i > 0) {
        if (list[i]['create_time_format'] ==
            list[i - 1]['create_time_format']) {
          list[i]['create_time_format'] = '';
        }
      }
    }
    list = list.reversed.toList();
    loading = false;
    setState(() {});
    refreshController.refreshCompleted();
    if (pagination.hasMore) {
      refreshController.loadComplete();
    } else {
      refreshController.loadNoData();
    }
  }

  setRead(item) async {
    if (item['isRead'] != true) {
      var res = await Http.instance.post('/plugin/messager/api/setRead', data: {
        "id": item['id'],
      });
      if (res.code == 1) {
        item['isRead'] = true;
      }
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(chattingName),
      ),
      body: UiLifeCycle(
        onRouteDone: () {
          fetchData();
        },
        child: loading
            ? const UiLoading()
            : list.isEmpty
                ? const Center(
                    child: UiResult(
                      text: '暂无消息',
                    ),
                  )
                : EasyRefresh(
                    onLoad: pagination.hasMore
                        ? () {
                            if (pagination.hasMore) {
                              pagination.currentPage++;
                              fetchData();
                            }
                          }
                        : null,
                    onRefresh: () {},
                    header: ListenerHeader(
                      listenable: listenable,
                      triggerOffset: 100000,
                      clamping: false,
                    ),
                    footer: BuilderFooter(
                        triggerOffset: 60,
                        clamping: false,
                        position: IndicatorPosition.above,
                        infiniteOffset: null,
                        processedDuration: Duration.zero,
                        builder: (context, state) {
                          return Stack(
                            children: [
                              SizedBox(
                                height: state.offset,
                                width: double.infinity,
                              ),
                              Positioned(
                                bottom: 0,
                                left: 0,
                                right: 0,
                                child: Container(
                                  alignment: Alignment.center,
                                  width: double.infinity,
                                  height: 30,
                                  child: pagination.hasMore
                                      ? const Row(
                                          mainAxisAlignment:
                                              MainAxisAlignment.center,
                                          children: [
                                            CupertinoActivityIndicator(
                                              radius: 8,
                                            ),
                                            SizedBox(width: 5),
                                            Text(
                                              '正在加载',
                                              style:
                                                  TextStyle(color: Colors.grey),
                                            )
                                          ],
                                        )
                                      : Text(
                                          '已加载完毕',
                                          style: TextStyle(
                                              color: Colors.grey[600]),
                                        ),
                                ),
                              )
                            ],
                          );
                        }),
                    child: ListView.builder(
                      reverse: true,
                      shrinkWrap: _shrinkWrap,
                      clipBehavior: Clip.none,
                      physics: _shrinkWrap
                          ? const NeverScrollableScrollPhysics()
                          : null,
                      itemBuilder: (context, index) {
                        return itemView(index);
                      },
                      itemCount: list.length,
                    ),
                  ),
      ),

      ///  bottomNavigationBar: footerView(),
    );
  }

  Widget? footerView() {
    return loading || list.isEmpty
        ? null
        : Container(
            color: UiTheme(context).match(
              light: Colors.white,
              dark: Theme.of(context).scaffoldBackgroundColor,
            ),
            child: SafeArea(
              bottom: true,
              top: false,
              minimum: const EdgeInsets.only(bottom: 15),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  const Divider(height: 0),
                  Container(
                    padding: const EdgeInsets.only(top: 15, bottom: 5),
                    child: const Text('全部标记已读'),
                  ),
                ],
              ),
            ),
          );
  }

  Widget itemView(index) {
    var item = list[index];

    if (item['msg_type'] == 'media') {
      return mediaView(item);
    }
    return infoView(item);
  }

  Widget infoView(item) {
    return Column(
      children: [
        if (Ui.isNotEmpty(item['create_time_format']))
          Padding(
            padding: const EdgeInsets.only(top: 10, bottom: 5),
            child: Text(
              '${item['create_time_format'] ?? '--'}',
              textAlign: TextAlign.center,
              style: const TextStyle(
                color: Colors.grey,
                fontSize: 12,
              ),
            ),
          ),
        UiTap(
          onTap: () {
            setRead(item);
            App.push(item['url']);
          },
          child: UiPanel(
            width: double.infinity,
            padding: const EdgeInsets.symmetric(horizontal: UiTheme.spacingX),
            margin: const EdgeInsets.symmetric(
              horizontal: UiTheme.spacingX,
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisSize: MainAxisSize.max,
              children: [
                Padding(
                  padding: const EdgeInsets.symmetric(vertical: 10),
                  child: Row(
                    children: [
                      if (item['isRead'] != true)
                        Container(
                          width: 10,
                          height: 10,
                          margin: const EdgeInsets.only(right: 10),
                          decoration: BoxDecoration(
                            color: Colors.red,
                            borderRadius: BorderRadius.circular(5),
                          ),
                        ),
                      Expanded(
                        child: Text(
                          item['title'],
                          overflow: TextOverflow.ellipsis,
                          style: const TextStyle(
                            fontWeight: FontWeight.bold,
                            fontSize: 16,
                          ),
                        ),
                      )
                    ],
                  ),
                ),
                const Divider(height: 0),
                Container(
                  width: double.infinity,
                  padding: const EdgeInsets.symmetric(vertical: 15),
                  child: Text(
                    item['intro'] ?? '--',
                    maxLines: 3,
                    overflow: TextOverflow.ellipsis,
                    style: const TextStyle(
                      color: Colors.grey,
                    ),
                  ),
                ),
                const Divider(height: 0),
                const Padding(
                  padding: EdgeInsets.symmetric(vertical: 10),
                  child: Row(
                    children: [
                      Expanded(
                        child: Text(
                          '查看详情',
                          style: TextStyle(
                            fontSize: 14,
                          ),
                        ),
                      ),
                      Icon(
                        Icons.arrow_forward_ios,
                        size: 15,
                        color: Colors.grey,
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
        const SizedBox(height: 15),
      ],
    );
  }

  Widget mediaView(item) {
    return Column(
      children: [
        if (Ui.isNotEmpty(item['create_time_format']))
          Padding(
            padding: const EdgeInsets.only(top: 10, bottom: 5),
            child: Text(
              '${item['create_time_format'] ?? '--'}',
              textAlign: TextAlign.center,
              style: const TextStyle(
                color: Colors.grey,
                fontSize: 12,
              ),
            ),
          ),
        UiTap(
          onTap: () {
            setRead(item);
            App.push(item['url']);
          },
          child: UiPanel(
            width: double.infinity,
            margin: const EdgeInsets.symmetric(
              horizontal: UiTheme.spacingX,
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                AspectRatio(
                  aspectRatio: 21 / 9,
                  child: CachedNetworkImage(
                    imageUrl: item['image'],
                    fit: BoxFit.cover,
                  ),
                ),
                const SizedBox(height: 10),
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 10),
                  child: Text(
                    item['title'] ?? '--',
                    style: const TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: 18,
                    ),
                  ),
                ),
                const SizedBox(height: 5),
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 10),
                  child: Text(
                    item['intro'] ?? '--',
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                    style: const TextStyle(
                      color: Colors.grey,
                    ),
                  ),
                ),
                const SizedBox(height: 15),
              ],
            ),
          ),
        ),
        const SizedBox(height: 15),
      ],
    );
  }
}
